package main.api;

import main.Logman;
import main.RequestHelper;
import main.ResponseHelper;
import main.database.ScoreHelper;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
public class ScoreApi {
    @PostMapping("/api/submitscore")
    public ResponseEntity<?> submitScore(HttpServletRequest request) {
        String uuid = RequestHelper.getUserUUIDFromRequest(request);
        String strScore = null, articleId = null;

        Map<String, String[]> map = request.getParameterMap();
        if (map.containsKey("score")) {
            strScore = map.get("score")[0];
        }
        if (map.containsKey("articleid")) {
            articleId = map.get("articleid")[0];
        }

        String result;
        if (uuid == null || uuid.isEmpty()) {
            result = ResponseHelper.createBasicJsonObject(404, "只有登录的用户才能提交分数").toString();
        }
        else if (strScore == null || strScore.isEmpty()) {
            result = ResponseHelper.createBasicJsonObject(404, "没有任何内容提交").toString();
        }
        else if (articleId == null || articleId.isEmpty()) {
            result = ResponseHelper.createBasicJsonObject(404, "没有合格的文章id").toString();
        }
        else {
            try {
                float score = Float.parseFloat(strScore);
                int response = ScoreHelper.submitScore(uuid, articleId, score);
                if (response == 0) {
                    result = ResponseHelper.createBasicJsonObject(200, "分数提交成功").toString();
                }
                else {
                    result = ResponseHelper.createBasicJsonObject(200, "分数更新成功").toString();
                }
            }
            catch (NumberFormatException e) {
                Logman.fatal("输入的数字格式不正确：" + e.getStackTrace().toString());
                result = ResponseHelper.createBasicJsonObject(404, "输入的数字格式不对").toString();
            }
        }

        return ResponseEntity.ok(result);
    }
}
